package com.example.gty.service.Impl;

import com.example.gty.entity.Student;
import com.example.gty.entity.UserRole;
import com.example.gty.mapper.StudentMapper;
import com.example.gty.mapper.UserRoleMapper;
import com.example.gty.mapper.UsersMapper;
import com.example.gty.service.StudentSelfService;
import com.example.gty.utils.ResultVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class StudentSelfServiceImpl implements StudentSelfService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private ObjectMapper objectMapper = new ObjectMapper();

    //查询所有学生基本信息
    public List<Student> selectStudentSelfAll() {
        List<Student> students = studentMapper.selectAll();
        return students;
    }


    //修改学生基本信息
    public ResultVo updateStuSelf(Student student) {
        student.setCreateTime(new Date());
        int i = studentMapper.updateByPrimaryKey(student);
        if (i > 0) {
            return new ResultVo(1000, "success", null);
        }
        return null;

    }

    //关键字模糊查询学生基本信息
    public List<Student> selectStudentKey(String key) {
        /*String s="%"+key+"%";
        List<Student> students = studentMapper.selectStudentKey(s);
        return students;*/
        try {
            List<Student> list = new ArrayList<>();
            SearchRequest searchRequest = new SearchRequest("studentinfo");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //关键词 字段名
            searchSourceBuilder.query(QueryBuilders.multiMatchQuery(key, "sno", "sname", "cclass", "major", "tel", "college"));
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //高亮字段
            HighlightBuilder.Field field1 = new HighlightBuilder.Field("sno");
            HighlightBuilder.Field field2 = new HighlightBuilder.Field("sname");
            HighlightBuilder.Field field3 = new HighlightBuilder.Field("cclass");
            HighlightBuilder.Field field4 = new HighlightBuilder.Field("major");
            HighlightBuilder.Field field5 = new HighlightBuilder.Field("tel");
            HighlightBuilder.Field field6 = new HighlightBuilder.Field("college");

            highlightBuilder.field(field1);
            highlightBuilder.field(field2);
            highlightBuilder.field(field3);
            highlightBuilder.field(field4);
            highlightBuilder.field(field5);
            highlightBuilder.field(field6);

            highlightBuilder.preTags("<font color='red' size='60px'>");
            highlightBuilder.postTags("</font>");
            //设置高亮
            searchSourceBuilder.highlighter(highlightBuilder);
            //存放查询要求
            searchRequest.source(searchSourceBuilder);
            //执行检索
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            SearchHits hits = search.getHits();
            //获得记录条数
            //int value = (int)hits.getTotalHits().value;
            Iterator<SearchHit> iterator = hits.iterator();
            while (iterator.hasNext()) {

                SearchHit hit = iterator.next();
                //转化为json字符串
                String stu = hit.getSourceAsString();
                Student student = objectMapper.readValue(stu, Student.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                /*Set<String> set = highlightFields.keySet();
                for (String s : set) {
                    String s1 = Arrays.toString(highlightFields.get(s).fragments());
                }*/
                //sno
                if (highlightFields.get("sno")!=null){
                    student.setSno(Arrays.toString(highlightFields.get("sno").fragments()));
                }
                HighlightField sname = highlightFields.get("sname");
                //sname
                if (sname!=null){
                    String s = Arrays.toString(sname.fragments());
                    student.setSname(s);
                }
                if (highlightFields.get("cclass")!=null){
                    student.setCclass(Arrays.toString(highlightFields.get("cclass").fragments()));
                }
                if (highlightFields.get("major")!=null){
                    student.setMajor(Arrays.toString(highlightFields.get("major").fragments()));
                }
                if (highlightFields.get("college")!=null){
                    student.setCollege(Arrays.toString(highlightFields.get("college").fragments()));
                }

                list.add(student);


            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    //批量删除学生信息
    public ResultVo deleteMultiStu(String snos) {
        String[] split = snos.split(",");
        System.out.println(split);
        //批量删除用户
        int i = usersMapper.deleteMultiUser(split);
        //批量删除用户角色
        int i1 = userRoleMapper.deleteMultiUR(split);
        //批量删除学生
        int i2 = studentMapper.deleteMuliStu(split);

        DeleteRequest request = new DeleteRequest("studentinfo");
        //删除es
        try {
            for (String s : split) {
                request.id(s);
                DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (i > 0 && i1 > 0 && i2 > 0)
            return new ResultVo(1000, "success", null);

        else return null;
    }
}
